package com.fjh.controller;

import com.fjh.pojo.Activity;
import com.fjh.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/activities")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @PostMapping
    public Activity createActivity(@RequestBody Activity activity) {
        return activityService.createActivity(activity);
    }

    @PutMapping
    public Activity updateActivity(@RequestBody Activity activity) {
        return activityService.updateActivity(activity);
    }

    @PostMapping("/{activityId}/publish")
    public void publishActivity(@PathVariable Long activityId) {
        activityService.publishActivity(activityId);
    }

    @GetMapping
    public List<Activity> getAllActivities() {
        return activityService.getAllActivities();
    }

    @GetMapping("/search")
    public List<Activity> searchActivities(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status
    ) {
        return activityService.searchActivities(name, status);
    }

    @GetMapping("/{activityId}")
    public Activity getActivityById(@PathVariable Long activityId) {
        return activityService.findActivityById(activityId);
    }

    @GetMapping("/add-activity")
    public String showAddActivityForm(Model model) {
        model.addAttribute("activity", new Activity());
        return "add-activity";
    }

    @PostMapping("/add-activity")
    public String addActivity(@ModelAttribute("activity") Activity activity, Model model) {
        activityService.addActivity(activity);
        model.addAttribute("activity", new Activity()); // 添加新的空Activity对象到模型
        return "redirect:/activities/query-activities";
    }


    @GetMapping("/query-activities")
    public String showActivities(Model model, HttpSession session) {
        List<Activity> activities = activityService.getAllActivities();
        model.addAttribute("activities", activities);

        // 添加登录用户信息到模板
        model.addAttribute("loggedInUser", session.getAttribute("loggedInUser"));

        return "query-activities";
    }


}
